package com.kamilparzych.pl.manageMyCost;

import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.datanucleus.store.exceptions.NullValueException;

import com.kamilparzych.pl.manageMyCost.data.CostEntry;
import com.kamilparzych.pl.manageMyCost.data.PMF;

@SuppressWarnings("serial")
public class ManageMyCostServlet extends HttpServlet {

	private static final String TYPE = "type";
	private static final String COST = "cost";
	private static final String DESCRIPTION = "desc";
    private static final Map<String, String> COST_TYPES = createMap();
    
    private static Map<String, String> createMap() {
    	Map<String, String> map = new HashMap<String, String>();
    	map.put("1", "Artykuly spozywcze");
    	map.put("2", "Odziez");
    	map.put("3", "Benzyna");
    	map.put("4", "Szkola");
    	map.put("5", "Dom");
    	map.put("6", "Prezenty");
    	map.put("7", "Rozrywka");
    	map.put("8", "Inne");
    	return Collections.unmodifiableMap(map);
    };

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try {
			this.doPost(req, resp);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html");
		final String typeKey = (String) req.getParameter(TYPE);
		final String type = COST_TYPES.get(typeKey);
		final String cost = (String) req.getParameter(COST);
		final String description = (String) req.getParameter(DESCRIPTION);
		final Date date = new Date();
		
		if ("".equals(type) || type==null || "null".equals(type) ||
		    "".equals(cost) || cost==null || "null".equals(cost)) {
			throw new NullValueException("There are empty values in cost or type. Please fill the values in.");
		}
		
		final CostEntry costEntry = new CostEntry(type, cost, description, date);
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		try
		{
			pm.makePersistent(costEntry);
		}
		catch (final NullValueException e)
		{
			resp.getWriter().println(
					"<div>" +
					e.getMessage() +
					"<a href=\"/request.html\">Back</a>" +
					"</div>");
		}
		catch (final Exception e)
		{
			e.printStackTrace(resp.getWriter());
		}
		finally
		{
			pm.close();
			resp.getWriter().println("Pomyslnie dokonano wpisu <br />");
			resp.getWriter().println("<a href=request.html>Powrot</a>");
		}
	}
}
